const Koa = require("koa");
const KoaRouter = require("@koa/router");

const app = new Koa();

const jwt = require("jsonwebtoken");
/*
 * alg 对称加密算法 采用同一个密钥 缺点分布式系统，
 * JWT 非对称加密
 */


const userRouter = new KoaRouter({ prefix: "/users" });

const secretkey = "aaabbccc";

userRouter.get("/login", (ctx, next) => {
  // 颁发token
  const playload = { id: "ff", name: "li" };
  const token = jwt.sign(playload, secretkey, {
    // 过期时间 秒
    expiresIn: 60,
  });

  ctx.body = {
    code: 0000,
    msg: "登陆成功",
    token,
  };
});

userRouter.get("/list", (ctx, next) => {
  // 验证用户的登录凭证: 携带口号 ikun
  const authorization = ctx.headers.authorization;
  const token = authorization.replace("Bearer ", "");
  // console.log(token);
  ctx.body = {
    msg: "登陆成功",
  };

  try {
    const result = jwt.verify(token, secretkey);
    console.log(result);
  } catch (err) {
    ctx.body = {
      msg: "token过期",
    };
  }
});

app.use(userRouter.routes());
app.use(userRouter.allowedMethods());

app.listen(8000, () => {
  console.log("服务器启动成功~");
});
